package edu.usc.libtalk;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;
import android.widget.AdapterView.OnItemClickListener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;

import edu.usc.libtalk.utils.ApplicationService;

public class LibTabMapActivity extends MapActivity implements LocationListener, SensorEventListener {

	private Drawable marker1;
	private Drawable marker2;
	private Drawable marker3;
	private Drawable marker4;
	
    private MapView mapView = null;;
//	private MapController mapController;
   
    private MyLocationOverlay me = null;
    
	private float mLastX, mLastY, mLastZ;
	private boolean mInitialized;

	private SensorManager mSensorManager;
	private Sensor mAccelerometer;

	private final float NOISE = (float) 2.0;    
	
    @Override
	protected boolean isLocationDisplayed() {
		// TODO Auto-generated method stub
		return super.isLocationDisplayed();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected int onGetMapDataSource() {
		// TODO Auto-generated method stub
		return super.onGetMapDataSource();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		me.disableCompass();
		me.disableMyLocation();
		mSensorManager.unregisterListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		me.enableCompass();
		me.enableMyLocation();
		mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	}

	/*
	protected void onScrollChanged(int pL, int pT, int pOldl, int pOldt) {
		if (pL < -500)
			scrollTo(-500, pT);
		super.onScrollChanged(pL, pT, pOldl, pOldt);
	}
	*/
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lib_tab_map);
        
        mapView = (MapView)findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(false);
        mapView.setSatellite(false);

        mapView.getController().setCenter(getPoint(34.021369,-118.2863628));

        mapView.getController().setZoom(17);
       
        
        
        me = new MyLocationOverlay(this, mapView);
        me.getMyLocation();
        mapView.getOverlays().add(me);
        mapView.postInvalidate();
        setZoomSize();
        
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			mapView.getController().setCenter(me.getMyLocation());

    		}
    	});    	
        
        ZoomControls zoomControls = (ZoomControls)findViewById(R.id.zoomControls1);
        
        zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	mapView.getController().zoomIn();
            	setZoomSize();
            	
            }
        });
        zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 mapView.getController().zoomOut();
                 setZoomSize();
             }
        });
        
        mapView.setOnTouchListener(new OnTouchListener() 
        {
             @Override
             public boolean onTouch(View v, MotionEvent event) 
             {
                 setZoomSize();
                 return false;
             }
        });
        
        
        mInitialized = false;
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);        
        if(mAccelerometer == null)
        {
        	Log.e("SENSOR", "Registered Sensor failed");
        }      
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);        
       
	}

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    	
    	// can be safely ignored for this demo
    } 
    
    public void onSensorChanged(SensorEvent event) {
	    
    	float x = event.values[0];
    	float y = event.values[1];	
	    float z = event.values[2];	    	   
    	
	    
	    if (!mInitialized) {
	    		    	
	    	mLastX = x;
		    mLastY = y;
		    mLastZ = z;
		    
		    mInitialized = true;
		//    Log.i("SENSOR", String.format("%f:%f:%f", x, y, z));
		    
	    } else {
		    float deltaX = Math.abs(mLastX - x);
		    float deltaY = mLastY - y;
		    float deltaY2 = y - mLastY;
		    float deltaZ = Math.abs(mLastZ - z);
		    
		    if (deltaX < NOISE) deltaX = (float)0.0;
		    if (deltaY < NOISE) deltaY = (float)0.0;
		    if (deltaZ < NOISE) deltaZ = (float)0.0;
		    
		    mLastX = x;
		    mLastY = y;
		    mLastZ = z;
		   	
		    
		    if (deltaY > 2.5){  
		    
		    	mapView.getController().zoomOut();
            	setZoomSize();
            
		    }
		    if (deltaY2 > 2.5){
		    		mapView.getController().zoomIn();
	            	setZoomSize();
	            
		    }
		   }
		    //Log.i("SENSOR", String.format("%f:%f:%f", x, y, z));
		    
		    
	    }

    	
	
	public void setZoomSize(){

		
        if(mapView.getZoomLevel() <= 18){
        		marker1 = this.getResources().getDrawable(R.drawable.ic_leavy_front3);
            marker2 = this.getResources().getDrawable(R.drawable.ic_leavy_front3);
            marker3 = this.getResources().getDrawable(R.drawable.ic_doheny_front3);
            marker4 = this.getResources().getDrawable(R.drawable.ic_leavy_front3);
         System.out.println("+=======================");
            	
        }
        else if((mapView.getZoomLevel() > 18) && (mapView.getZoomLevel() <= 19)){
        		marker1 = this.getResources().getDrawable(R.drawable.ic_leavy_front2);
            marker2 = this.getResources().getDrawable(R.drawable.ic_leavy_front2);
            marker3 = this.getResources().getDrawable(R.drawable.ic_doheny_front2);
            marker4 = this.getResources().getDrawable(R.drawable.ic_leavy_front2);
           
            
        }
        else if((mapView.getZoomLevel() > 19) && (mapView.getZoomLevel() <= 20)){
        		marker1 = this.getResources().getDrawable(R.drawable.ic_leavy_front1);
            marker2 = this.getResources().getDrawable(R.drawable.ic_leavy_front1);
            marker3 = this.getResources().getDrawable(R.drawable.ic_doheny_front1);
            marker4 = this.getResources().getDrawable(R.drawable.ic_leavy_front1);
          
            
        }
        else if(mapView.getZoomLevel() > 20){
    		marker1 = this.getResources().getDrawable(R.drawable.ic_leavy_front);
        marker2 = this.getResources().getDrawable(R.drawable.ic_leavy_front);
        marker3 = this.getResources().getDrawable(R.drawable.ic_doheny_front);
        marker4 = this.getResources().getDrawable(R.drawable.ic_leavy_front);
      
        
    }
        
        
        marker1.setBounds(0, 0, marker1.getIntrinsicWidth(),
                marker1.getIntrinsicHeight());
        marker2.setBounds(0, 0, marker2.getIntrinsicWidth(),
                marker2.getIntrinsicHeight());
        marker3.setBounds(0, 0, marker3.getIntrinsicWidth(),
                marker3.getIntrinsicHeight());
        marker4.setBounds(0, 0, marker4.getIntrinsicWidth(),
                marker4.getIntrinsicHeight());
        
        mapView.getOverlays().clear();
       
        me.getMyLocation();
        mapView.getOverlays().add(me);
        
        
        mapView.getOverlays().add(new SitesOverlay(marker1));
        mapView.getOverlays().add(new SitesOverlay(marker2));
        mapView.getOverlays().add(new SitesOverlay(marker3));
        mapView.getOverlays().add(new SitesOverlay(marker4));
               
        
	}
	
	
	
	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	@Override
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_S) {
	      mapView.setSatellite(!mapView.isSatellite());
	      return(true);
	    }
	    else if (keyCode == KeyEvent.KEYCODE_Z) {
	      mapView.displayZoomControls(true);
	      return(true);
	    }
	    
	    return(super.onKeyDown(keyCode, event));
	  }

	  private GeoPoint getPoint(double lat, double lon) {
	    return(new GeoPoint((int)(lat*1000000.0),
	                          (int)(lon*1000000.0)));
	  }
	    
	  private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
	    private List<OverlayItem> items=new ArrayList<OverlayItem>();
	    
	    public List getitems(){
			return items;
	    	
	    }
	    
	    public SitesOverlay(Drawable marker) {
	      super(marker);
	      
	   //   boundCenterBottom(marker);
	     if (marker == marker1){
	    	  items.add(new OverlayItem(getPoint(34.019581,
		    		  -118.288723),"SAL","Seaver Science Library"));
	    	  populate();
	     }
	     else if(marker == marker2){
	    	 items.add(new OverlayItem(getPoint(34.021804,
	    			 -118.282956),"LVL", "Leavey Library"));
	    	 populate();
	     }
	     else if(marker == marker3){
	    	 items.add(new OverlayItem(getPoint(34.020079,
	    			 -118.28368),"DML","Edward L Doheny Memorial LibraryLincoln Center"));
	    	 populate();
	     }
	     else if(marker == marker4){
	    	 items.add(new OverlayItem(getPoint(34.021167,
	    			 -118.283911),"VKC","Von KleinSmid Center Library"));
	    	 populate();
	     }
	    
	      
	    }
	    
	    @Override
	    protected OverlayItem createItem(int i) {
	      return(items.get(i));
	    }
	    
	    @Override
	    protected boolean onTap(int i) {
	    	
	    		setZoomSize();
	      Intent intent = new Intent(LibTabMapActivity.this, SignInActivity.class);
	      ApplicationService.setLibrary(items.get(i).toString());
	      startActivity(intent);
	      return(true);
	    }
	    
	    @Override
	    public int size() {
	      return(items.size());
	    }
	  }
	  
	
	  
}

    
	
	
